package cn.demomaster.quicklogger.util

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.core.content.ContextCompat
import cn.demomaster.quicklogger.QdLog
import cn.demomaster.quicklogger.QdLog.Companion.PERMISSION_MANAGE_EXTERNAL
import cn.demomaster.quicklogger.QdLog.Companion.PERMISSION_WRITE_EXTERNAL
import cn.demomaster.quicklogger.config.LogConfig

class PermissionUtil {

    companion object {
        fun checkPermissionStatus(context: Context, permissions: String): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && permissions == Manifest.permission.MANAGE_EXTERNAL_STORAGE) {
                val p = Environment.isExternalStorageManager()
                return p // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            } else {
                if (permissions == Manifest.permission.MANAGE_EXTERNAL_STORAGE) {
                    return true
                }
                val r = ContextCompat.checkSelfPermission(context.applicationContext, permissions)
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                return (r == PackageManager.PERMISSION_GRANTED)
            }
        }

        fun checkWritePermission(context: Context, mConfig: LogConfig): Boolean {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                return if (mConfig!!.saveExternalStorageAfterAndroidQ) { //强制使用外置存储 针对Android Q以上的版本，但是需要 MANAGE_EXTERNAL_STORAGE
                    checkPermissionStatus(
                        context,
                        PERMISSION_WRITE_EXTERNAL
                    ) && PermissionUtil.checkPermissionStatus(context, PERMISSION_MANAGE_EXTERNAL)
                } else {
                    true
                }
            } else {
                if (mConfig!!.saveExternalStorageBeforeAndroidQ) { //使用外置存储
                    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
                        if (Environment.isExternalStorageLegacy()) {
                            return checkPermissionStatus(
                                context,
                                PERMISSION_WRITE_EXTERNAL
                            )
                        } else {
                            Log.e(
                                mConfig!!.TAG,
                                "请在Manifest添加： android:requestLegacyExternalStorage=\"true\""
                            )
                            return false
                        }
                    } else {
                        return checkPermissionStatus(
                            context,
                            PERMISSION_WRITE_EXTERNAL
                        )
                    }
                } else {
                    return true
                }
            }
        }
    }
}